import { defineStore } from 'pinia'
import { ref } from 'vue'
import type { MenuItem, loginResponseData } from '@/types/user'

export const useUserStore = defineStore('user', () => {
  const userInfo = ref<loginResponseData['userInfo'] | Record<string, never>>({})
  const token = ref('')
  const menuList = ref<MenuItem[]>([])
  const hasRoutes = ref(false) // 标记是否已添加动态路由

  // 设置用户信息
  const setUserInfo = (info: loginResponseData['userInfo']) => {
    userInfo.value = info
  }

  // 设置token
  const setToken = (tokenValue: string) => {
    token.value = tokenValue
  }

  // 设置菜单列表
  const setMenuList = (menus: MenuItem[]) => {
    menuList.value = menus
  }

  // 设置路由状态
  const setHasRoutes = (status: boolean) => {
    hasRoutes.value = status
  }

  // 清除用户数据
  const clearUserData = () => {
    userInfo.value = {}
    token.value = ''
    menuList.value = []
    hasRoutes.value = false
  }

  return {
    userInfo,
    token,
    menuList,
    hasRoutes,
    setUserInfo,
    setToken,
    setMenuList,
    setHasRoutes,
    clearUserData
  }
}, {
  persist: {
    key: 'user-store',
    storage: localStorage,
    pick: ['userInfo', 'token', 'menuList'] // 只持久化这些字段，hasRoutes 不需要持久化
  }
})
